import { App, navigate, mall, toast } from '../../../../library/api/index'

Page({
  data: {
    navMe: 'on',
    tip: 'blank',
    tipData: {},
    address: {},
    orderId: '',
    order: {}
  },
  onLoad: function(e) {
    this.setData({
      orderId: e.order_id
    })
    App.jice.onLoad(e)
  },
  onReady: function() {
    this.getOrder()
    App.jice.track('page', {
      pagepath: '/pages/me/order/settlement/index',
      pageTitle: '个人中心-订单-结算',
      pageType: 'view'
    })
    App.logger({
      type: App.G.view,
      channel: App.G.channel,
      target: '个人中心-订单-结算'
    })
  },
  onShow: function() {
    this.getUserAddress()
    App.jice.track('appshow')
  },
  getOrder: function() {
    mall.getOrder(this.data.orderId, r => {
      if(r.code == 200) {
        this.setData({
          order: r.data
        })
      } else if(r.code >= 400) {
        this.showErrorTip(r.data)
      }
    }, r => {
      this.showErrorTip(`系统错误[${r.message}]，请稍后再试~`)
    })
  },
  getUserAddress: function() {
    mall.getAddress(r => {
      if(r.code == 200) {
        this.setData({
          address: r.data
        })
      } else if(r.code >= 400) {
        this.showErrorTip(r.data)
      }
    }, r => {
      this.setData({
        tip: 'error_tip',
        tipData: `系统错误，请稍后再试~`
      })
    })
  },
  goAddress: function() {
    navigate.to(`/pages/mall/address/index?back=${encodeURIComponent(`/pages/me/order/settlement/index?order_id=${this.data.orderId}`)}`)
  },
  pay: function() {
    toast.show(5000)
    mall.saveOrder({
      type: this.data.order.type,
      address: JSON.stringify(this.data.address),
      products: JSON.stringify(this.data.order.products)
    }, r => {
      if(r.code == 200) {
        console.log(r)
        this.prepay(r.order_id, 0)
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  },
  prepay: function(orderId, resetPayNo) {
    mall.prepayOrder(orderId, resetPayNo, r => {
      if(r.code == 200) {
        console.log(r.data)
        this.weAppPay(r.data)
      } else if(r.code == 510064) {
        this.setData({
          tip: 'order_expire',
          tipData: '支付失败，订单已失效，请您重新选择商品下单！'
        })
      } else if(r.code == 510500) {
        this.setData({
          tip: 'order_expire',
          tipData: '支付失败，订单中有商品已经被下架了，请您重新选择商品下单！'
        })
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  },
  weAppPay: function(order) {
    var data = {
      appid: App.G.Appid,
      mch_id: App.G.MchId,
      order_id: order.orderid,
      pay_no: order.payno,
      fee: this.data.order.fee
    }
    mall.payOrder(data, r => {
      toast.close(0)
      if(r.code == 200) {
        wx.requestPayment({
          timeStamp: r.pay.timeStamp + '',
          nonceStr: r.pay.nonceStr,
          package: r.pay.package,
          signType: r.pay.signType,
          paySign: r.pay.paySign,
          success: res => {
            console.log(res)
            this.showErrorTip('支付成功，感谢您的支持，我们会尽快安排发货')
            setTimeout(() => {
              navigate.reload(`/pages/me/order/list/index`)
            }, 3000)
          },
          fail: res => {
            console.log(res)
            this.showErrorTip(`您取消了支付，您可以点击支付重新支付~`)
          }
        })
      }
      if(r.code == 502) {
        this.showErrorTip(r.data)
      }
      if(r.code == 210 || r.code == 211) {
        this.prepay(order.orderid, 1)
      }
      if(r.code == 202) {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  },
  showErrorTip: function(message) {
    this.setData({
      tip: 'error_tip',
      tipData: message
    })
  },
  closeTip: function() {
    this.setData({
      tip: 'blank',
      tipData: {}
    })
  },
  goMall: function() {
    navigate.redirect('/pages/mall/index')
  },
  minus: function(e) {
    let pid = e.currentTarget.dataset.pid
    for(let m = 0; m < this.data.order.products.length; m++) {
      if(this.data.order.products[m].id == pid) {
        this.data.order.products[m].count -= 1
        if(this.data.order.products.length > 1 && this.data.order.products[m].count == 0) {
          this.data.order.products.splice(m, 1)
        } else if(this.data.order.products.length == 1 && this.data.order.products[m].count == 0) {
          navigate.redirect('/pages/mall/milk/index')
          return
        }
        break
      }
    }

    let total = 0
    let fee = 0
    for(let n = 0; n < this.data.order.products.length; n++) {
      total += this.data.order.products[n].count
      fee += this.data.order.products[n].count * this.data.order.products[n].my_price
    }
    this.data.order.count = total
    this.data.order.fee = (fee * 100) / 100

    this.setData({
      order: this.data.order
    })

    mall.saveOrder({
      type: this.data.order.type,
      address: JSON.stringify(this.data.address),
      products: JSON.stringify(this.data.order.products)
    }, r => {
      if(r.code == 200) {
        console.log(r)
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  },
  add: function(e) {
    let pid = e.currentTarget.dataset.pid
    for(let m = 0; m < this.data.order.products.length; m++) {
      if(this.data.order.products[m].id == pid) {
        this.data.order.products[m].count += 1
        break
      }
    }

    let total = 0
    let fee = 0
    for(let n = 0; n < this.data.order.products.length; n++) {
      total += this.data.order.products[n].count
      fee += this.data.order.products[n].count * this.data.order.products[n].my_price
    }
    this.data.order.count = total
    this.data.order.fee = (fee * 100) / 100

    this.setData({
      order: this.data.order
    })
    mall.saveOrder({
      type: this.data.order.type,
      address: JSON.stringify(this.data.address),
      products: JSON.stringify(this.data.order.products)
    }, r => {
      if(r.code == 200) {
        console.log(r)
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  }
})